package org.oneblog.controller;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.oneblog.controller.util.NetUtils;
import org.oneblog.data.bean.AlbumSubs;
import org.oneblog.data.bean.AlbumView;
import org.oneblog.data.query.AlbumQuery;
import org.oneblog.data.query.ArticleSolrQuery;
import org.oneblog.data.rs.Result;
import org.oneblog.data.service.IArticleSolrService;
import org.oneblog.data.util.StringTools;
import org.oneblog.service.IAlbumService;
import org.oneblog.service.IArticleService;
import org.oneblog.service.IImageService;
import org.oneblog.view.ArticleView;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/*
 * 微信小程序数据接口
 */
@Controller("AppDataController")
@RequestMapping("/app")
public class AppDataController extends SessionController {

	private List<ArticleView> cutStringForApp(List<ArticleView> list, int maxLen) {
		if (CollectionUtils.isEmpty(list)) {
			return new ArrayList<>(0);
		}
		for (ArticleView v : list) {

			v.setTags(StringTools.subList(v.getTags(), 3));

			v.setContent(StringTools.cutForABC(v.getContent(), maxLen));
		}
		return list;
	}

	// 列表
	@RequestMapping(value = "/homelist")
	@Cacheable(value="blogCache", key="#query.key() + '_' + #maxLen + '_' + #type + '_' + #albums")
	public @ResponseBody Result<ArticleView> homelist(HttpServletRequest request,
			@RequestParam(value = "maxLen", defaultValue = "", required = false) String maxLen,
			@RequestParam(value = "type", defaultValue = "", required = false) String type,
			@RequestParam(value = "albums", defaultValue = "", required = false) String albums,
			@ModelAttribute ArticleSolrQuery query) {

		try {

			int atType = StringTools.getInt(type, 1);
			Result<ArticleView> articles = new Result<>();

			switch (atType) {

			case 1:// 最新
				articles = articleService.queryArticles(query);
				break;
			case 2:// 热门
				articles.setList(articleService.hotArticles());
				break;
			case 3:// 推荐
				articles.setList(articleService.priorityArticles());
				break;

			default:
				break;
			}

			cutStringForApp(articles.getList(), StringTools.getInt(maxLen, 200));

			if (StringTools.getInt(albums, -1) > 0) {
				AlbumQuery albumQuery = new AlbumQuery();
				albumQuery.setViewDefuncted(0);
				albumQuery.setPageNo(1);
				albumQuery.setPageSize(6);
				albumQuery.setViewSubs(0);
				articles.setAlbums(albumService.getAlbums(albumQuery));
			}

			return articles;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	// 专辑
	@Cacheable(value="blogCache", key="#query.key()")
	@RequestMapping(value = "/albums")
	public @ResponseBody List<AlbumView> albums(HttpServletRequest request,
			@ModelAttribute AlbumQuery query) {

		try {
			List<AlbumView> albums = albumService.getAlbums(query);
			
			return albums;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Cacheable(value="blogCache", key="#albumId")
	@RequestMapping(value = "/albumDetail")
	public @ResponseBody AlbumView albumDetail(HttpServletRequest request,
			@RequestParam(value = "albumId", defaultValue = "", required = true) String albumId) {

		try {
			AlbumView albumView = albumService.detail(albumId);
			
			List<AlbumSubs> articles = albumView.getArticles();
			if(articles != null && articles.size() > 0) {
				for(AlbumSubs s : articles) {
					String c = s.getContent();
					c = StringTools.delHTMLTag(c);
					if(StringUtils.isNotBlank(c)) {
						if(c.length() > 100) {
							c = c.substring(0, 100);
						}
					}
					s.setContent(c);
				}
			}
			
			return albumView;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Cacheable(value="blogCache", key="#articleId")
	@RequestMapping(value = "/articleDetail")
	public @ResponseBody ArticleView articleDetail(HttpServletRequest request,
			@RequestParam(value = "atclid", defaultValue = "", required = true) String articleId) {

		try {
			ArticleView detail = articleService.detail(articleId);

			return detail;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

    //赞
    @RequestMapping(value = "/good")
    @ResponseBody
    public Object good(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute ArticleSolrQuery query) {

        try {
            InetAddress localAddress = NetUtils.getLocalAddress();
            String localIp = localAddress != null ? localAddress.getHostAddress() : "127.0.0.1";
            
            int rs = articleService.setGood(query.getId(), NetUtils.getIpAddr(request), localIp);
            
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return 0;
    }
    
    //一天内是否设置过good
    @RequestMapping(value = "/isGood")
    @ResponseBody
    public Object isGood(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute ArticleSolrQuery query) {

        try {
            return isGood(request, query.getId()) ? 1 : 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return 0;
    }
    
    @Resource(name = "cacheManager")
    private EhCacheCacheManager cacheManager;
    
	@Resource(name = "articleService")
	IArticleService articleService;

	@Resource(name = "articleSolrService")
	private IArticleSolrService articleSolrService;

	@Resource(name = "imageService")
	private IImageService imageService;

	@Resource(name = "albumService")
	private IAlbumService albumService;
}
